package core;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.Timer;

import superweapons.SuperWeapon;

public class SuperweaponController implements ActionListener {
	private JButton button;
	private Timer availableTimer, secondTimer;
	private String name;
	private boolean isAvailable;
	private int timeRemaining;
	
	private Model model;
	private Controller controller;

	public SuperweaponController(Controller c, Model model, String name, ImageIcon icon, int rechargeTime) {
		timeRemaining = rechargeTime / 1000;
		this.model = model;
		this.controller = c;
		
		button = new JButton(icon);
		button.addActionListener(this);
		button.setPreferredSize( new Dimension(50, 25) );
		button.setFocusable( false );
		button.setToolTipText("Cooldown remaining: "+getTimeRemaining());
		button.setEnabled(false);
		
		availableTimer = new Timer(rechargeTime, this);
		availableTimer.setRepeats(false);
		availableTimer.start();
		
		secondTimer = new Timer(1000, this);
		secondTimer.setRepeats(true);
		secondTimer.start();
		
		this.name = name;
	}

	public void resetTimer() {
		button.setEnabled(false);
		timeRemaining = availableTimer.getDelay() / 1000;
		isAvailable = false;
		availableTimer.restart();
	}
	
	public void startTimer() {
		availableTimer.start();
	}
	
	public void stopTimer() {
		availableTimer.stop();
	}
	
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == availableTimer) {
			button.setToolTipText(name + " is ready for use!");
			button.setEnabled(true);
			isAvailable = true;
		} else if (e.getSource() == button) {
			activate();
		} else if (e.getSource() == secondTimer && availableTimer.isRunning()) {
			button.setToolTipText("Cooldown remaining: "+getTimeRemaining());
		}
	}

	public void activate() {
		if (isAvailable) {
			try {
				SuperWeapon weapon = (SuperWeapon) Class.forName("superweapons."+name).newInstance();
				if (weapon.isAimed()) {
					controller.activateSuperWeapon(weapon);
				} else {
					model.buySuperWeapon(weapon, null);
				}
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public String getName() {
		return name;
	}

	public JButton getButton() {
		return button;
	}
	
	public String getTimeRemaining() {
		timeRemaining--;
		int minutes = timeRemaining / 60;
		int seconds = timeRemaining % 60;
		return (minutes+":"+(seconds<10?"0":"")+seconds);
	}

	public Timer getAvailableTimer() {
		return availableTimer;
	}

	public Timer getSecondTimer() {
		return secondTimer;
	}
}
